<template>
  <div id="mine-set">
    <section>
      <div class="avatar this-public-row" @click="actionSheetShow()">
        <span class="tag">头像设置</span>
        <div class="this-public-right">
          <img
            v-if="avatar !== 'null'"
            :src="avatar"
            alt="">
          <img
            v-else="avatar === null"
            src="../../assets/images/mine/icon-avatar.png"
            alt="">
          <span class="arrow">></span>
        </div>
      </div>
      <div class="tel this-public-row" @click="beforeModify(newTel)">
        <span class="tag">修改手机号</span>
        <div class="this-public-right">
          <span class="tel-num">{{ tel }}</span>
          <span class="arrow">></span>
        </div>
      </div>
    </section>

    <ul>
      <li
        class="this-public-row"
        v-for="(item, index) in ulList"
        :key="index"
        @click="beforeModify(item.then)">
        <span class="tag">{{ item.text }}</span>
        <span class="arrow">></span>
      </li>
    </ul>

    <button @click="quit">退出账号</button>

    <input
      type="file"
      id="avatar_image"
      name="avatar_image"
      accept="image/*"
      @change="uploadFile($event)">

    <popup
      v-model="telPopupShow"
      v-if="telPopupShow"
      position="top"
      class="telPopup">
      <form action="" id="mine-set-newTel-form">
        <ul>
          <li>
            <div class="wrap">
              <label for="tel">新手机号：</label>
              <input
                type="tel"
                id="tel"
                name="新手机号"
                v-model.trim="newTelNum"
                v-validate="'required|tel'">
            </div>
            <span v-show="VeeErrors.has('新手机号')">{{ VeeErrors.first('新手机号') }}</span>
          </li>
          <li>
            <div class="wrap">
              <label for="code">验证码：</label>
              <input
                type="text"
                id="code"
                name="验证码"
                v-model.trim="code"
                v-validate="'required|numeric'">
              <button
                @click.prevent="getCode"
                :disabled="getCodeBtnPressed"
                :class="{'disable': getCodeBtnPressed}">{{ getCodeBtnText }}</button>
            </div>
            <span v-show="VeeErrors.has('验证码')">{{ VeeErrors.first('验证码') }}</span>
          </li>
        </ul>

        <input
          type="button"
          value="确定"
          :disabled="confirmTelDisabled"
          @click="confirmTel">
      </form>
    </popup>
  </div>
</template>

<script>
  import { Toast, MessageBox, Popup } from 'mint-ui';
  export default {
    name: "item-mine-set",
    components: {
      Popup
    },
    data() {
      return {
        validated: false,
        avatar: localStorage.getItem('avatar'),
        tel: localStorage.getItem('mobile'),
        telPopupShow: false,
        newTelNum: '',
        code: '',
        getCodeBtnText: '获取',
        getCodeBtnPressed: false,
        confirmTelDisabled: false,
        ulList: [
          {
            text: '修改登录密码',
            then: this.newPSW
          },
          {
            text: '修改提现密码',
            then: this.newWithdrawPSW
          },
          {
            text: '新增提现账号',
            then: this.newAccount
          }
        ]
      }
    },
    methods: {

      // 0
      // 验证登录密码

      beforeModify(then) {
        if (!this.validated) {
          MessageBox.prompt('请先验证当前的登录密码', '提示', {
            inputType: 'password',
            inputValidator: (value) => {
              if (!value) {
                return '密码不能为空.';
              }
            }
          }).then(({ value, action }) => {
            this.$http.post({
              api: this.$api.USER_LOGIN,
              params: {
                mobile: localStorage.getItem('mobile'),
                password: value
              },
              success: (res) => {
                this.$tool.whenToast(
                  () => {
                    localStorage.setItem('token', res.data.data.token);
                    this.validated = true;
                  },
                  {
                    message: '验证成功',
                    duration: -1,
                    iconClass: 'public-toast-icon success'
                  },
                  () => {
                    then();
                  },1200
                );
              },
              failure: function (res) {
                Toast(res.data.msg);
              }
            })
          });
        } else {
          then();
        }
      },

      // 系统操作弹出

      actionSheetShow() {
        this.$tool.clickIdDom('avatar_image');
      },

      // 1
      // 头像

      uploadFile(event) {

        // 提示正在上传

        Toast({
          message: '图片火速上传中...',
          duration: 2000
        });

        let formData = new FormData();
        formData.append('file',event.target.files[0]);
        this.$http.axios({
          url: this.$http.avatarURL,
          method:'post',
          data: formData
        }).then((res) => {
          if (res.data.error === 0) {

            this.$http.post({
              api: this.$api.USER_SET,
              params: {
                user_id: localStorage.getItem('id'),
                type: 1,
                data: [
                  {
                    avatar: res.data.data.avatar
                  }
                ]
              },
              success: function (res) {
                setTimeout(() => {
                  Toast('头像上传成功');

                  // 使用localStorage存储头像

                  localStorage.setItem('avatar', res.data.data.avatar);

                  // 实时更新头像

                  this.avatar = res.data.data.avatar;
                }, 1000);
              }.bind(this)
            });
          } else if (res.data.error === 1) {
            alert(res.data.msg);
          }
        }).catch((error) => {
          console.log(error);
        })
      },

      // 2
      // 手机号

      newTel() {

        // 初始化

        this.code = '';

        this.telPopupShow = true;
      },

      // 获取验证码

      getCode() {

        // 1 - 先验证是否已填写手机号

        this.$validator.validate('新手机号').then((result) => {
          if (result) {

            // 置灰

            this.getCodeBtnPressed = true;

            // 请求验证码

            this.$http.post({
              api: this.$api.USER_CODE,
              params: {
                mobile: this.newTelNum
              },
              success: (res) => {

                this.countDown();

                Toast({
                  message: res.data.msg,
                  position: 'top',
                  className: 'public-long-toast public-topZ-toast'
                });
              },
              failure: (res) => {
                this.countDown();

                Toast({
                  message: res.data.msg,
                  position: 'top',
                  className: 'public-long-toast public-topZ-toast'
                });
              }
            })
          }
        });
      },

      // 倒计时

      countDown() {
        let seconds = 60;
        this.getCodeBtnText = seconds + 's';
        let countDown = setInterval(() => {
          this.getCodeBtnText = --seconds + 's';

          if (seconds === 0) {
            clearInterval(countDown);

            // 取消置灰

            this.getCodeBtnPressed = false;

            // 恢复提示

            this.getCodeBtnText = '获取';
          }
        }, 1000);
      },

      // 确定修改手机号

      confirmTel() {
        this.$validator.validateAll().then((result) => {

          // 1 - form 验证通过

          if (result) {

            //  提交更改

            this.$http.post({
              api: this.$api.USER_SET,
              params: {
                user_id: localStorage.getItem('id'),
                type: 2,
                data: [
                  {
                    mobile: this.newTelNum, code: this.code
                  }
                ]
              },
              success: (res)=> {

                this.$tool.whenToast(
                  () => {

                    // 关闭弹出框

                    this.telPopupShow = false;

                    // 使用localStorage存储手机号

                    localStorage.setItem('mobile', this.newTelNum);

                    // 禁止重复点击确定按钮

                    this.confirmTelDisabled = true;
                  },
                  {
                    message: res.data.msg,
                    duration: 2000
                  },
                  () => {

                    // 更新手机号信息、恢复点击

                    this.tel = localStorage.getItem('mobile');
                    this.confirmTelDisabled = false;
                  },2000
                );

//                // 关闭弹出框
//
//                this.telPopupShow = false;
//
//                // 使用localStorage存储手机号
//
//                localStorage.setItem('mobile', this.newTelNum);
//
//                // 禁止重复点击确定按钮
//
//                this.confirmTelDisabled = true;
//
//                // toast提示
//
//                Toast({
//                  message: res.data.msg,
//                  position: 'center',
//                  duration: 2000
//                });
//
//                // 更新手机号信息、恢复点击
//
//                setTimeout(() => {
//                  this.tel = localStorage.getItem('mobile');
//                  this.confirmTelDisabled = false;
//                }, 2000);
              }
            });
          } else {

            // 2 - form 验证不通过

            this.$tool.whenToast(
              () => {

                // 暂时禁用确定按钮

                this.confirmTelDisabled = true;
              },
              {
                message: '请完善修改信息',
                position: 'top',
                className: 'public-topZ-toast',
                duration: -1
              },
              () => {
                // 恢复确定按钮

                this.confirmTelDisabled = false;
              },2000
            );
          }
        });
      },

      // 3
      // 登录密码

      newPSW() {
        MessageBox.prompt('请输入新的登录密码', '提示', {
          inputType: 'password',
          inputPattern: /^[A-Za-z0-9]+$/,
          inputErrorMessage: '密码由字母或数字组成'
        }).then(({value, action}) => {
          this.$http.post({
            api: this.$api.USER_SET,
            params: {
              user_id: localStorage.getItem('id'),
              type: 3,
              data: [
                {
                  password: value
                }
              ]
            },
            success: function (res) {

              // 提示

              Toast(res.data.msg);

            }
          })
        });
      },

      // 4
      // 提现密码

      newWithdrawPSW() {
        MessageBox.prompt('请输入新的提现密码', '提示', {
          inputType: 'password',
          inputPattern: /^[A-Za-z0-9]+$/,
          inputErrorMessage: '密码由字母或数字组成'
        }).then(({value, action}) => {
          this.$http.post({
            api: this.$api.USER_SET,
            params: {
              user_id: localStorage.getItem('id'),
              type: 4,
              data: [
                {
                  password: value
                }
              ]
            },
            success: function (res) {

              // 提示

              Toast(res.data.msg);
            }
          })
        });
      },

      // 5
      // 提现账号

      newAccount() {
        this.$router.push('/new-account');
      },

      // 退出账号
      quit() {
        MessageBox.confirm('确定退出此账户?').then(action => {
          if (action === 'confirm') {
            localStorage.clear();
            window.WeixinJSBridge ? WeixinJSBridge.call('closeWindow') : this.$router.push('/login');
          }
        });
      }
    }
  }
</script>

<style lang="scss">

  #mine-set {

    $this-public-border: 1px solid #eee;
    $this-public-padding: 0 1rem;
    $this-public-grey: #a9a9a9;

    $icon-avatar-side: 4rem;
    $exit-btn-height: 5rem;

    .this-public-row {
      display: flex;
      justify-content: space-between;
      align-items: center;

      >.tag {
        font-size: 1.5rem;
        color: #333;
      }

      .arrow {
        margin-left: .6rem;
        font-size: 2rem;
        color: $this-public-grey;
      }
    }

    .this-public-right {
      display: flex;
      align-items: center;
    }

    >section {
      padding: $this-public-padding;
      margin: 1rem 0;
      background: $white;

      >.avatar {
        height: 6.5rem;
        border-bottom: $this-public-border;

        img {
          display: inline-block;
          width: $icon-avatar-side;
          height: $icon-avatar-side;
          border-radius: 50%;
        }
      }

      >.tel {
        height: 4rem;

        .tel-num {
          font-size: 1.5rem;
          color: $this-public-grey;
        }
      }
    }

    >ul {
      padding: $this-public-padding;
      margin-bottom: 6rem;
      background: $white;

      >li {
        height: 4rem;
        border-bottom: $this-public-border;

        &:last-of-type {
          border: none;
        }
      }
    }

    >button {
      width: $size-as-parent;
      height: $exit-btn-height;
      line-height: $exit-btn-height;
      font-size: 1.8rem;
      font-weight: bold;
      text-align: center;
      color: #f00;
      border-top: $this-public-border;
      border-bottom: $this-public-border;
      background: $white;
    }

    >#avatar_image {
      display: none;
    }

    >.telPopup {

      $icon-width: 12px;
      $row-height: 28px;
      $row-font-size: 1.6rem;
      $confirm-height: 3.9rem;

      width: $size-as-parent;
      top: 50%;
      left: 50%;
      -webkit-transform: translate3d(-50%, -50%, 0);
      transform: translate3d(-50%, -50%, 0);
      background: none;

      >form {
        width: 68%;
        padding: 4rem 2rem 4rem;
        margin: $margin-auto;
        border-radius: 8px;
        background: $white;

        li {
          position: relative;
          padding-left: .8rem;
          margin-bottom: 4rem;
          border-bottom: 1px solid #4e4e4e;

          >.wrap {
            display: flex;
            align-items: center;
            height: $row-height;
            line-height: $row-height;

            >label {
              min-width: 86px;
              font-size: $row-font-size;
              color: #333;
              text-indent: .8rem;
              padding-left: $icon-width;
              background: url("../../assets/images/entrance/icons.png") no-repeat center / $icon-width auto;
            }

            >input {
              flex: 1;
              height: $size-as-parent;
              font-size: $row-font-size;
              color: #000;
              min-width: 0; // hack
            }

            >button{
              width: 52px;
              height: 24px;
              padding: 0 8px;
              font-size: 1.2rem;
              color: $white;
              text-align: center;
              border-radius: 12px;
              background: #c3ebff;

              &.disable {
                color: $white;
                background: #bbb;
              }
            }
          }

          >span {
            position: absolute;
            right: 0;
            top: $size-as-parent;
            color: #e4393c;
          }

          &:nth-of-type(1) > .wrap > label {
            background-position: 0 7px;
          }

          &:nth-of-type(2) > .wrap > label {
            background-position: 0 -57px;
          }
        }

        >input {
          width: $size-as-parent;
          height: $confirm-height;
          line-height: $confirm-height;
          font-size: 1.8rem;
          color: #fff;
          text-align: center;
          border-radius: 6px;
          background: #0097ff;
        }

      }
    }
  }
</style>
